<template>
  <!-- No changes to template section -->
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 跳转到新增发票页面
const goToInvoiceAdd = (order: Order) => {
  // 跳转到新增发票页面，并携带订单编号等参数
  router.push({
    path: "/contract/tInvoice/add",
    query: {
      orderNumber: order.number,
      orderId: order.id,
      amount: order.amount,
      buyerName: order.order_type === "采购订单" ? "" : "", // 可根据业务补充
      sellerName: order.order_type === "采购订单" ? "" : "" // 可根据业务补充
    }
  });
};

// 开票对话框相关状态
const invoiceDialogVisible = ref(false);
const currentInvoiceOrder = ref<Order | null>(null);
const invoiceForm = reactive({
  buyerName: "",
  buyerAddress: "",
  buyerTaxNum: "",
  buyerPhone: "",
  email: "",
  goodsName: "水费",
  quantity: "1",
  unit: "吨"
});

// 打开开票对话框
const openInvoiceDialog = (order: Order) => {
  currentInvoiceOrder.value = order;
  invoiceForm.buyerName = "";
  invoiceForm.buyerAddress = "";
  invoiceForm.buyerTaxNum = "";
  invoiceForm.buyerPhone = "";
  invoiceForm.email = "";
  invoiceForm.goodsName = "水费";
  invoiceForm.quantity = "1";
  invoiceForm.unit = "吨";
  invoiceDialogVisible.value = true;
};

// 提交开票申请
const submitInvoice = async () => {
  if (!currentInvoiceOrder.value) return;
  
  if (!invoiceForm.buyerName.trim()) {
    ElMessage.error("请输入购方名称");
    return;
  }

  try {
    const params = new URLSearchParams();
    params.append("orderNo", currentInvoiceOrder.value.number);
    params.append("buyerName", invoiceForm.buyerName);
    params.append("buyerAddress", invoiceForm.buyerAddress);
    params.append("buyerTaxNum", invoiceForm.buyerTaxNum);
    params.append("buyerPhone", invoiceForm.buyerPhone);
    params.append("email", invoiceForm.email);
    params.append("amount", currentInvoiceOrder.value.amount.toString());
    params.append("goodsName", invoiceForm.goodsName);
    params.append("quantity", invoiceForm.quantity);
    params.append("unit", invoiceForm.unit);

    const response = await fetch("/api/tInvoice/applyByOrder", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": `Bearer ${localStorage.getItem("accessToken")}`
      },
      body: params
    });

    const result = await response.json();
    
    if (result.success) {
      ElMessage.success("发票申请成功！");
      invoiceDialogVisible.value = false;
      // 更新订单的开票状态
      await loadOrderData();
    } else {
      ElMessage.error(result.msg || "发票申请失败");
    }
  } catch (error) {
    console.error("开票申请失败:", error);
    ElMessage.error("开票申请失败，请稍后重试");
  }
};
</script> 